<!--<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>-->
<template>
    <div>
        <header class="resviseTop" id="kfus">
            <img src="../../images/left.png" alt="" onclick="javascript :history.back(-1);">
            <span class="resvise_title">客服会话</span>
        </header>

        <div class="chatContainer">
            <div class="chatBox" ref="chatBox">
                <div class="chatBox-info" >
                    <div class="chatBox-kuang" ref="chatBoxkuang">
                        <div class="chatBox-content">
                            <div class="chatBox-content-demo" id="chatBox-content-demo" >
                                <!--append-->
                                <div v-if="timeline" id="scrolls">
                                    <div class="clearfloat" v-for="data in timeline">
                                        <div class="author-name">
                                            <small class="chat-date">{{ data.created_at }}</small>
                                        </div>
                                        <div class="right" style="width: 100%" v-if="data.from_type == 1"> <div class="chat-message" v-html="data.msg"></div>
                                            <div class="chat-avatars">
                                                <img :src="user_avatar" alt="头像" />
                                            </div>
                                        </div>
                                        <div v-else>
                                            <p class="anminName">{{ adminname }}</p>
                                            <div class="left">
                                                <div class="chat-avatars"><img src="https://imgshangjia.renqidaren.com/uploads/20190111/60eb12a837fb5eaf9674adfd0df0f5ae.png" alt="头像"></div>
                                                <div class="chat-message" v-html="data.msg"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>

        <div class="chatBox-send">
            <div>
                <button id="chat-biaoqing" class="btn-default-styles">
                    <img src="../../images/qq.png" alt="">
                </button>

                <label id="chat-tuxiang" title="发送图片" class="btn-default-styles">
                    <input type="file"  @change="selectImg"  accept="image/jpg,image/jpeg,image/png"  action="" ref='panel' name="file" class="hidden">
                    <img src="../../images/imgsrc.png" alt=""  >
                </label>
            </div>
            <div class="spend">
                <textarea class="div-textarea" ref="html"></textarea>
                <button id="chat-fasong" class="btn-default-styles"  @click="fasong">
                    发送
                </button>
            </div>
            <div class="biaoqing-photo" style="display: none;">
                <ul>
                    <li><span class="emoji-picker-image" style="background-position: -9px -18px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -40px -18px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -71px -18px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -102px -18px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -133px -18px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -164px -18px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -9px -52px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -40px -52px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -71px -52px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -102px -52px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -133px -52px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -164px -52px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -9px -86px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -40px -86px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -71px -86px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -102px -86px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -133px -86px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -164px -86px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -9px -120px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -40px -120px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -71px -120px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -102px -120px;"></span>
                    </li>
                    <li><span class="emoji-picker-image" style="background-position: -133px -120px;"></span>
                    </li>
                    <li><span class="emoji-picker-image" style="background-position: -164px -120px;"></span>
                    </li>
                    <li><span class="emoji-picker-image" style="background-position: -9px -154px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -40px -154px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -71px -154px;"></span></li>
                    <li><span class="emoji-picker-image" style="background-position: -102px -154px;"></span>
                    </li>
                    <li><span class="emoji-picker-image" style="background-position: -133px -154px;"></span>
                    </li>
                    <li><span class="emoji-picker-image" style="background-position: -164px -154px;"></span>
                    </li>
                </ul>
            </div>
        </div>
        <!--end ！-->
    </div>
</template>
<script>
    import api from '../../utils/api';
    import {GenNonDuplicateID} from '@/utils/config';
    import axios from 'axios'
    let OSS = require('ali-oss');

    export default {
        name: "service",
        data:()=>({
            lessw:'',
            ws:null,
            msg: "",
            file_data:'',
            adminId:'',
            image_src:'',
            token: '',
            hui_speak:'',
            timeline:[],
            client_id:'',
            html:'',
            adminname:'',
            workid:'',
            user_avatar:'',
            user_name:'',
            oss_config:[]
        }),
        mounted(){
            screenFuc();
            this.WebSocket();
            function screenFuc() {
                var topHeight = $(".chatBox-head").innerHeight();//聊天头部高度
                //屏幕小于768px时候,布局change
                var winWidth = $(window).innerWidth();
                if (winWidth <= 768) {
                    var totalHeight = $(window).height(); //页面整体高度
                    $(".chatBox-info").css("height", totalHeight - topHeight);
                    var infoHeight = $(".chatBox-info").innerHeight();//聊天头部以下高度
                    //中间内容高度
                    $(".chatBox-content").css("height", infoHeight - 90);
                    $(".chatBox-content-demo").css("height", infoHeight - 140);
                    $(".chatBox-kuang").css("height", totalHeight - topHeight);
                }
            }
            (window.onresize = function () {
                screenFuc();
            })();
            // 发送表情
            var that =this;
            $(".emoji-picker-image").each(function () {
                $(this).click(function () {
                    var bq = $(this).parent().html();
                    var emijo = {
                        'msg':bq,
                        "id":that.adminId
                    }
                    let resp =  api.request('/customer_service/send', 'post',emijo)
                    $(".chatBox-content-demo").append(
                        ` <div class="clearfloat">
                            <div class="right">
                             <p>${that.user_name}</p>
                               <div class="chat-message">${bq}</div>
                               <div class="chat-avatars">
                                    <img src="${that.user_avatar}" alt="头像" />
                                </div>
                            </div>
                        </div>`
                    );
                    //发送后关闭表情框
                    $(".biaoqing-photo").toggle();
                    //聊天框默认最底部
                    setTimeout(function(){
                        $(document).ready(function () {
                            $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                        });
                    },500)
                })
            });
            $(".div-textarea").blur(function () {
                $("html,body").animate({scrollTop: document.documentElement.clientHeight},500);
            });
            $("#chat-biaoqing").click(function () {
                $(".biaoqing-photo").toggle();
            });
            $(document).click(function () {
                $(".biaoqing-photo").css("display", "none");
            });
            $("#chat-biaoqing").click(function (event) {
                event.stopPropagation();//阻止事件
            });
        },
        methods:{
            //发送按钮
            fasong:function(){
                var textContent = this.$refs.html.value.replace(/[\n\r]/g, '<br>')
                this.msg = textContent;
                this.send()
            },
            //发送信息
            send(){
                var that = this;
                var fd = {
                    "msg":that.msg,
                    "id":that.adminId
                }
                var aa=  this.msg;
                let resp =  api.request('/customer_service/send', 'post',fd).then(res=>{
                    if (this.msg != "") {
                        //发送后清空输入框
                        $(".div-textarea").val("");
                        $(".chatBox-content-demo").append(
                            `<div class="clearfloat">
                            <div class="author-name"><small class="chat-date">${res.data.data.created_at}<small> </div>
                               <p>${that.user_name}</p>
                            <div class="right" style="width: 100%"> <div class="chat-message">${aa}</div>
                               <div class="chat-avatars">
                                 <img src="${that.user_avatar}" alt="头像" />
                           </div>

                            </div>
                         </div> `
                        );
                        //聊天框默认最底部
                        $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                    }
                })
            },
            async previewOSS(name, file) {
                let resp = await api.request('/oss_config', 'get', {})
                let data = resp.data.data;
                let par = {
                    region: 'oss-cn-shanghai',
                    accessKeyId: data.accessKeyId,
                    accessKeySecret: data.accessKeySecret,
                    bucket: data.bucket
                }
                this.oss_config = par
            },
            async   selectImg(pic) {
                var that =  this;
                function preview1(file) {
                    var img = new Image(), url = img.src = URL.createObjectURL(file)
                    var $img = $(img)
                    that.image_src = $img.context.src;
                    img.onload = function () {
                        URL.revokeObjectURL(url)
                    }
                }
                var file = pic.target.files[0];
                that.file_data = file
                preview1(file)
                let client = new OSS(this.oss_config);
                let result =  await client.put(GenNonDuplicateID(32), file);

                var divImg =   ` <img src="${result.url}"> `
                var fds = {
                    "msg":divImg,
                    "id":that.adminId
                }
                let resp =  await api.request('/customer_service/send', 'post',fds).then(res=>{
                    $(".chatBox-content-demo").append(
                        `<div class="clearfloat">
                                         <p>${that.user_name}</p>
                                        <div class="right">
                                            <div class="chat-message">
                                                <img src="${result.url}">
                                            </div>
                                            <div class="chat-avatars">
                                                <img src="${that.user_avatar}" alt="头像"" alt="头像" />
                                            </div>
                                            </div>
                                             </div>`
                    );
                })
                //聊天框默认最底部
                setTimeout(function(){
                    $(document).ready(function () {
                        $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                    });
                },500)
            },
            WebSocket() {
                var that = this;
                if(window.location.href.indexOf('h5-master.hetaojiazu') != -1){
                    this.ws = new WebSocket("wss://console-master.hetaojiazu.cn:2347")
                }else{
                    this.ws = new WebSocket("wss://socket.woyaorenqi.com:2347")
                }
                // this.ws = new WebSocket("wss://socket.woyaorenqi.com:2347")
                this.ws.onopen = function () {
                }
                this.ws.onmessage = function (ev) {
                    console.log(ev,"suerimgs")
                    var item = JSON.parse(ev.data)
                    if(item.type=='bindUid'){
                        let respw =  api.request('/customer_service/binduid', 'post', {'client_id': item.client_id})
                    }else if(item.type=='newMsg'){
                        that.html = item.data.msg
                    }
                    that.hui_speak = item;
                }
            },
            admin_id:function(){
                var that = this;
                let resp =  api.request('/customer_service/getservice', 'get',{}).then(res=>{
                    if(res.code==400){
                        return
                    }
                    that.adminId = res.data.data.administrator_id
                    that.adminname = res.data.data.administrator_name
                    api.request('/customer_service/timeline', 'get',{ type:2,id:res.data.data.administrator_id}).then(res=>{
                        that.timeline = res.data.data;
                        that.token = that.GetQueryString("token")    //获取参数
                        if(that.GetQueryString("workid") && that.GetQueryString("consumerid")){
                            that.msg = '子任务ID(' + that.GetQueryString("workid") + ') 任务号(' + this.$route.query.consumerid + ')'
                            that.send()
                        }else{
                            that.msg=''
                        }

                    })
                })
            },
            GetQueryString:function(name) {
                var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if(r!=null)return  unescape(r[2]); return null;
            }
        },
        created() {
            this.previewOSS();
            var that = this;
            this.admin_id();
            let resp =  api.request('/user', 'get',{}).then(res=>{
                console.log(res,"userts")
                that.user_avatar=res.data.data.user_avatar;
                that.user_name=res.data.data.user_wechat_nickname
            })
        },
        watch: {
            hui_speak(newValue) {
                var that = this;
                if(newValue.type == 'newMsg'){
                    var hui_html = newValue.data.msg;
                    var created_at= newValue.data.created_at
                    var form_id = newValue.data.from_id
                    $(".chatBox-content-demo").append(
                        `<div class="clearfloat">
                                    <div class="author-name">
                                    <small class="chat-date">${created_at}</small>
                                </div>
                                <p class="anminName">${that.adminname}</p>
                                <div class="left">
                                    <div class="chat-avatars"><img src="https://imgshangjia.renqidaren.com/uploads/20190111/60eb12a837fb5eaf9674adfd0df0f5ae.png" alt="头像"></div>
                                    <div class="chat-message">
                                         ${that.html}
                                    </div>
                                    </div>
                                </div> `
                    )
                    $(document).ready(function () {
                        $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                    });
                }
            },
            timeline: function() {
                this.$nextTick(function(){
                   setTimeout(function(){
                       $(document).ready(function () {
                           $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                       });
                   },500)
                })
            }

        },
    }

</script>

<style>
    @import "../../style/chat.css";
    @import "../../style/iconfont.css";
</style>
